package com.sf.ams.sqlfile;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.sf.ams.constant.Constant;
import com.sf.ams.entity.Environment;
import com.sf.ams.entity.SystemInfo;
import com.sf.ams.entity.enums.SystemExceptionType;
import com.sf.ams.exception.SqlFileHandlerException;
import com.sf.ams.utils.ExecutorStatusMapUtil;

/**
 * 描述：
 * 对从GIT拉取或者上传的文件的解压后的文件收集，用于后面组成SQL字符串然后执行做准备
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年10月25日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
public abstract class BaseSqlFileHandler {
	protected List<Environment> environments;
	protected SystemInfo system;
	
	public BaseSqlFileHandler(List<Environment> environments, SystemInfo system) {
		this.environments = environments;
		this.system = system;
	}

	protected static final String BASE_SQLCODE_PATH = Constant.LOCAL_CODE_DIR + Constant.PATH_SPLIT_CHARACTOR;
	public List<File> processSqlFile() throws SqlFileHandlerException{
		List<File> sqlFiles = new ArrayList<>();
		environments.forEach(e -> 
		ExecutorStatusMapUtil.setExecutorStauts(system.getSystemCode() + "_" + e.getEnvironmentType(), SystemExceptionType.COMMONING)
		);
		boolean updateCodeFlag = writeFileToLocal();
		
		if( !updateCodeFlag ) {
			throw new SqlFileHandlerException("从GIT中拉取代码或者解压文件失败");
		}
		//更新代码成功,然后开始执行脚本
		String sqlCodePath = sqlCodePath();
		File sqlFolder = new File(sqlCodePath.replace("/", Constant.PATH_SPLIT_CHARACTOR));
		if (!sqlFolder.exists()) {
			environments.forEach(e -> 
			ExecutorStatusMapUtil.setExecutorStauts(system.getSystemCode() + "_" + e.getEnvironmentType(), SystemExceptionType.SQLPATHEXCPTION)
			);
			throw new SqlFileHandlerException("SQL文件路径不存在!");
		}
		sqlFiles.addAll(Arrays.asList(sqlFolder.listFiles()));
		if(sqlFiles.isEmpty()){
			environments.forEach(e -> 
			ExecutorStatusMapUtil.setExecutorStauts(system.getSystemCode() + "_" + e.getEnvironmentType(), SystemExceptionType.NOSQLEXCEPTION)
			);
			throw new SqlFileHandlerException("SQL文件路径下没有文件!");
		}
		return sqlFiles;
	}
	protected abstract boolean writeFileToLocal();
	
	protected abstract String sqlCodePath();
}
